package com.soft.leo.oldbook;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.camera2.CaptureResult;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.yongchun.library.view.ImageSelectorActivity;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import cn.lankton.flowlayout.FlowLayout;


public class SubmitActivity extends AppCompatActivity {
    private ImageButton picSubmiter;
    private ArrayList<String> picList;
    private EditText isbnIn,commentIn,MoneyIn;
    private Button finSubBt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //region 浸入式标题栏
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        //endregion
        setContentView(R.layout.activity_submit);
        initComp();
        initFunc();

    }

    private void initFunc() {
        picSubmiter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ImageSelectorActivity.start(SubmitActivity.this, 9, ImageSelectorActivity.MODE_MULTIPLE, true,true,false);
            }
        });
        finSubBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitBook(picList,new ArrayList<AVFile>());

            }
        });
    }

    private void initComp() {
        picSubmiter=(ImageButton)findViewById(R.id.pic_submiter);
        isbnIn=(EditText)findViewById(R.id.isbnIn);
        commentIn=(EditText)findViewById(R.id.subComment);
        MoneyIn=(EditText)findViewById(R.id.subMoney);
        finSubBt=(Button)findViewById(R.id.finishSub_bt);
        picList=new ArrayList<>();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK && requestCode == ImageSelectorActivity.REQUEST_IMAGE) {
            ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
            Toast.makeText(SubmitActivity.this,images.toString(),Toast.LENGTH_SHORT);
            View picView=findViewById(R.id.piclayout);
            ((FlowLayout)picView).removeAllViews();
            picList=images;
            if(!images.isEmpty()){
                for (String str:images) {
                    try {
                        FileInputStream fis = new FileInputStream(str);
                        ImageButton img=new ImageButton(this);
                        ActionBar.LayoutParams layout=new ActionBar.LayoutParams(100,100);
                        layout.setMargins(20,20,20,20);
                        img.setLayoutParams(layout);
                        img.setBackground(new BitmapDrawable(BitmapFactory.decodeStream(fis)));
                        img.setPadding(20,20,20,20);
                        img.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                ImageSelectorActivity.start(SubmitActivity.this, 9, ImageSelectorActivity.MODE_MULTIPLE, true,true,false);
                            }
                        });
                        ((FlowLayout)picView).addView(img);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                }

            }

        }
    }

    public void submitBook(final ArrayList<String> files, final ArrayList<AVFile> readyFiles) {
        if (files.isEmpty()) {
            String isbn = isbnIn.getText().toString();
            String comment = commentIn.getText().toString();
            int money = 0;
            if (MoneyIn.getText().toString() != null)
                money = Integer.parseInt(MoneyIn.getText().toString());
            if (isbn == null)
                Toast.makeText(SubmitActivity.this, "请填写完整书籍编码(ISBN)", Toast.LENGTH_SHORT).show();
            else {
                AVObject object = new AVObject("Book");
                object.put("user", AVUser.getCurrentUser());
                object.put("isbn", isbn);
                object.put("comment", comment);
                object.put("pics", readyFiles);
                object.put("money", money);
                object.put("isSent", false);
                object.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        if (e == null) {
                            Toast.makeText(SubmitActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                        else
                            Toast.makeText(SubmitActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }else{
            final AVFile file;
            try {
                file = AVFile.withAbsoluteLocalPath(AVUser.getCurrentUser().getUsername()+"_book.png",files.get(0));
                file.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        if(e==null){
                            files.remove(0);
                            readyFiles.add(file);
                            submitBook(files,readyFiles);
                        }else{
                            Toast.makeText(SubmitActivity.this,e.toString(),Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

}
